<template>
  <div class="stats-display">
    <!-- 加载状态 -->
    <div v-if="isLoading.value" style="text-align: center; padding: 50px">
      <el-icon class="is-loading" :size="40"><Loading /></el-icon>
      <div style="margin-top: 16px">加载统计数据中...</div>
    </div>

    <!-- 无网站提示 -->
    <el-alert
      v-else-if="!website"
      message="未选择网站"
      description="请选择一个网站查看统计数据"
      type="info"
      :closable="false"
    />

    <!-- 统计数据展示 -->
    <template v-else>
      <!-- 统计摘要 -->
      <StatsSummary :summary="safeStats?.summary" />

      <!-- 时间范围选择器 -->
      <TimeRangeSelector 
        :time-range="props.timeRange || statsParams.timeRange"
        @time-range-change="handleTimeRangeChange"
      />

      <!-- 图表展示 -->
      <el-tabs v-model="activeChartTab" type="card" @tab-change="handleTabChange">
        <el-tab-pane label="访问趋势" name="trend">
          <TrendChart 
            v-if="activeChartTab === 'trend'"
            :data="safeStats?.data || []"
            :group-by="props.groupBy || statsParams.groupBy"
            @group-by-change="handleGroupByChange"
          />
        </el-tab-pane>
        
        <el-tab-pane label="来源分布" name="source">
          <DistributionChart 
            v-if="activeChartTab === 'source'"
            title="来源分布"
            :data="sourceData"
            type="pie"
            :color-map="sourceColorMap"
            :tooltip-formatter="sourceTooltipFormatter"
            empty-text="暂无来源分布数据"
          />
        </el-tab-pane>
        
        <el-tab-pane label="设备分布" name="device">
          <DistributionChart 
            v-if="activeChartTab === 'device'"
            title="设备分布"
            :data="deviceData"
            type="pie"
            :color-map="deviceColorMap"
            empty-text="暂无设备分布数据"
          />
        </el-tab-pane>
        
        <el-tab-pane label="浏览器分布" name="browser">
          <DistributionChart 
            v-if="activeChartTab === 'browser'"
            title="浏览器分布"
            :data="browserData"
            type="bar"
            empty-text="暂无浏览器分布数据"
          />
        </el-tab-pane>
        
        <el-tab-pane label="操作系统分布" name="os">
          <DistributionChart 
            v-if="activeChartTab === 'os'"
            title="操作系统分布"
            :data="osData"
            type="bar"
            empty-text="暂无操作系统分布数据"
          />
        </el-tab-pane>
        
        <el-tab-pane label="热门页面" name="url">
          <DistributionChart 
            v-if="activeChartTab === 'url'"
            title="热门页面"
            :data="urlData"
            type="bar"
            :tooltip-formatter="urlTooltipFormatter"
            empty-text="暂无URL分布数据"
          />
        </el-tab-pane>
      </el-tabs>
    </template>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, nextTick, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { Loading } from '@element-plus/icons-vue'
import { useTrackingStore } from '@/store/tracking'
import StatsSummary from './charts/StatsSummary.vue'
import TrendChart from './charts/TrendChart.vue'
import DistributionChart from './charts/DistributionChart.vue'
import TimeRangeSelector from './charts/TimeRangeSelector.vue'

interface Website {
  id: string | number
  name: string
  domain?: string
}

interface Props {
  website?: Website | null
  timeRange?: string
  groupBy?: string
}

const props = defineProps<Props>()

const emit = defineEmits<{
  timeRangeChange: [value: string]
  groupByChange: [value: string]
}>()

// 直接从 Pinia Store 读取数据
const trackingStore = useTrackingStore()
const { websiteStats, isLoading, statsParams } = storeToRefs(trackingStore)

const activeChartTab = ref('trend')

// 确保stats存在，如果不存在则提供默认空数据结构
const safeStats = computed(() => {
  return websiteStats.value || {
    summary: { totalPageViews: 0, uniquePageViews: 0, bounceRate: 0 },
    data: [],
    referrers: [],
    devices: [],
    browsers: [],
    os: [],
    countries: [],
    urls: []
  }
})

// 监听网站变化，确保数据加载
watch(() => props.website, (newWebsite: Website | null | undefined) => {
  if (newWebsite?._id) {
    trackingStore.fetchWebsiteStats(newWebsite._id, {
      timeRange: props.timeRange || statsParams.value.timeRange,
      groupBy: props.groupBy || statsParams.value.groupBy
    }).catch((err: any) => {
      console.error('[StatsDisplay] Failed to fetch stats:', err)
    })
  }
}, { immediate: true })

// 处理来源分布数据
const sourceData = computed(() => {
  const result = (safeStats.value.referrers || []).map((item: Record<string, any>) => {
    const referrer = item.referrer || item.pv_referrer || null
    let displayName = '直接访问'
    
    if (referrer) {
      try {
        const url = new URL(referrer)
        displayName = url.hostname
      } catch (e) {
        displayName = referrer
      }
    }
    
    return {
      type: displayName,
      value: Number(item.count) || 0,
      originalRef: referrer
    }
  }).filter(item => item.value > 0)
  
  return result
})

// 设备映射配置
const DEVICE_MAP: Record<string, { name: string; color: string }> = {
  'desktop': { name: '桌面端', color: '#409EFF' },
  'mobile': { name: '移动端', color: '#67C23A' },
  'tablet': { name: '平板端', color: '#E6A23C' },
  'unknown': { name: '未知设备', color: '#909399' }
}

// 处理设备分布数据
const deviceData = computed(() => {
  const result = (safeStats.value.devices || []).map((item: Record<string, any>) => {
    const deviceType = item.device || item.pv_device || null
    // 处理 null 值
    const actualDeviceType = deviceType !== null && deviceType !== undefined ? deviceType : 'unknown'
    const deviceInfo = DEVICE_MAP[actualDeviceType] || DEVICE_MAP.unknown
    
    return {
      type: deviceInfo.name,
      value: Number(item.count) || 0,
      color: deviceInfo.color,
      originalType: actualDeviceType
    }
  }).filter(item => item.value > 0)
  
  return result
})

// 浏览器映射配置
const BROWSER_MAP: Record<string, { color: string }> = {
  'Chrome': { color: '#4285f4' },
  'Firefox': { color: '#ff6b35' },
  'Safari': { color: '#0066cc' },
  'Edge': { color: '#0078d4' },
  'Opera': { color: '#ff1b2d' },
  'unknown': { color: '#909399' }
}

// 处理浏览器分布数据
const browserData = computed(() => {
  const result = (safeStats.value.browsers || []).map((item: Record<string, any>) => {
    const browserName = item.browser || item.pv_browser || null
    // 处理 null 值
    const actualBrowserName = browserName !== null && browserName !== undefined ? browserName : 'unknown'
    const browserInfo = BROWSER_MAP[actualBrowserName] || BROWSER_MAP.unknown
    const displayName = actualBrowserName !== 'unknown' ? actualBrowserName : '未知浏览器'
    
    return {
      type: displayName,
      value: Number(item.count) || 0,
      color: browserInfo.color
    }
  }).filter(item => item.value > 0)
  
  return result
})

// 操作系统映射配置
const OS_MAP: Record<string, { color: string }> = {
  'Windows': { color: '#0078d4' },
  'macOS': { color: '#000000' },
  'iOS': { color: '#007aff' },
  'Android': { color: '#3ddc84' },
  'Linux': { color: '#fcc624' },
  'unknown': { color: '#909399' }
}

// 处理操作系统分布数据
const osData = computed(() => {
  const result = (safeStats.value.os || []).map((item: Record<string, any>) => {
    const osName = item.os || item.pv_os || null
    // 处理 null 值
    const actualOsName = osName !== null && osName !== undefined ? osName : 'unknown'
    const osInfo = OS_MAP[actualOsName] || OS_MAP.unknown
    const displayName = actualOsName !== 'unknown' ? actualOsName : '未知系统'
    
    return {
      type: displayName,
      value: Number(item.count) || 0,
      color: osInfo.color
    }
  }).filter(item => item.value > 0)
  
  return result
})

// 格式化URL显示
const formatUrl = (url: string) => {
  if (!url) return '未知页面'
  try {
    const urlObj = new URL(url)
    return urlObj.pathname === '/' ? urlObj.hostname : urlObj.pathname
  } catch (e) {
    return url
  }
}

// 处理URL分布数据
const urlData = computed(() => {
  const result = (safeStats.value.urls || []).map((item: Record<string, any>) => {
    const url = item.url || item.pv_url || '未知页面'
    return {
      type: formatUrl(url),
      value: Number(item.count) || 0,
      originalUrl: url
    }
  }).filter(item => item.value > 0)
  
  return result
})

// 颜色映射
const sourceColorMap = {
  '直接访问': '#409EFF',
  'localhost': '#E6A23C',
  'google.com': '#4285f4',
  'bing.com': '#0078d4',
  'baidu.com': '#2932e1'
}

const deviceColorMap = {
  '桌面端': '#409EFF',
  '移动端': '#67C23A',
  '平板端': '#E6A23C',
  '未知设备': '#909399'
}

// Tooltip 格式化器
// echarts 传递的参数格式：{ name, value, data, ... }
// data 字段包含原始数据对象的所有字段
const sourceTooltipFormatter = (params: any) => {
  const datum = params.data || params
  const name = datum.type || datum.name || params.name || '未知'
  const value = datum.value || params.value || 0
  const originalRef = datum.originalRef
  
  return {
    name,
    value: `${value}${originalRef ? ` (${originalRef})` : ' (直接访问)'}`
  }
}

const urlTooltipFormatter = (params: any) => {
  const datum = params.data || params
  const name = datum.type || datum.name || params.name || '未知'
  const value = datum.value || params.value || 0
  const originalUrl = datum.originalUrl
  
  return {
    name,
    value: `${value}${originalUrl ? ` (${originalUrl})` : ''}`
  }
}

const handleTimeRangeChange = (value: string) => {
  emit('timeRangeChange', value)
}

const handleGroupByChange = (value: string) => {
  emit('groupByChange', value)
}

const handleTabChange = (tabName: string) => {
  setTimeout(() => {
    // 触发图表的重新渲染
    nextTick(() => {
      // 图表组件会在 nextTick 后自动初始化
    })
  }, 200)
}
</script>

<style scoped lang="scss">
.stats-display {
  padding: 20px;
}
</style>

